package com.seal.commons.core.entity.converter;

import com.seal.commons.core.SecretPropertiesUtils;
import com.seal.commons.utils.StringUtils;
import com.seal.commons.utils.security.AESUtils;
import org.springframework.core.io.FileSystemResource;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-06-16 21:13<br/>
 */
@Converter
public class EncryptConverter implements AttributeConverter<String, String> {

    /**
     * 用于敏感数据加解密，需要设置
     */
    public static final String ENCRYPT_KEY_NAME = "jpa.encrypt.key";


    @Override
    public String convertToDatabaseColumn(String encrypt) {
        return AESUtils.encrypt(encrypt, getEncryptKey());
    }

    @Override
    public String convertToEntityAttribute(String encrypt) {
        return AESUtils.decrypt(encrypt, getEncryptKey());
    }


    private String getEncryptKey(){
        String key = System.getProperty(ENCRYPT_KEY_NAME);
        if(StringUtils.isBlank(key)){
            key = SecretPropertiesUtils.getProperty(ENCRYPT_KEY_NAME);
            if(StringUtils.isBlank(key)){
                throw new IllegalArgumentException("jpa.encrypt.key not found");
            }
        }

        return key;
    }



}